package com.opengw.controller.processor;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.opengw.configuration.ConfigurationManager;
import com.opengw.configuration.route.Route;
import com.opengw.exception.OpenGWException;
import com.opengw.http.HTTPRequest;


public class PublishProcessor extends BaseProcessor{

	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try{
			ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager();
			Route route = configurationManager.getRoute(request.getRequestURI()); 
			
			if(route == null)
				throw new OpenGWException(OpenGWException.NOT_FOUND_RESOURCE, true);
			
			if(!route.getAvailableMethods().contains(request.getMethod().toUpperCase()))
				throw new OpenGWException(OpenGWException.FORBIDDEN_HTTP_METHOD, true); 
			
			if(route.isConfigBeforeRequest()){
				new HTTPRequest(request, route);
			} 
			
			response.setContentType(route.getDefaultContent().getContentType());
			OutputStream outputStream = response.getOutputStream();
			outputStream.write(route.getDefaultContent().getContent());
			outputStream.flush();
			
			
		} catch (OpenGWException e) {
			if(e.isHTTPResponseAvaiable()){
				e.getResponse().sendResponse(response);
			} else{
				RequestDispatcher dispatcher = request.getRequestDispatcher(e.getExceptionPage());
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher dispatcher = request.getRequestDispatcher(OpenGWException.DEFAULT_ERROR_PAGE);
			dispatcher.forward(request, response);
		}
		
	}

}
